package com.pine.dcts.websocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pine.dcts.common.DctsException;
import com.pine.dcts.entity.JobInfo;
import com.pine.dcts.log.JobLogReader;
import com.pine.dcts.service.JobService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author xiaoyuan
 * @create 2021/1/13 14:16
 **/
@Component("jobLog")
@Slf4j
public class JobLogWebSocketMessageHandler implements WebSocketMessageHandler, ApplicationContextAware {

    @Autowired
    private JobService jobService;
    //线程池
    private ExecutorService executorService = Executors.newCachedThreadPool();

    private ApplicationContext applicationContext;


    private static Map<String, Integer> lengthMap = new ConcurrentHashMap<>();


    @Override
    public void init(Session session, String key, String id) {
        JobInfo jobInfo = jobService.getById(id);
        if (jobInfo == null) {
            throw new DctsException("任务信息不存在");
        }
        executorService.submit(new JobLogReader(lengthMap.get(key),key,applicationContext));
    }

    @Override
    public void messageHandler(Session session, String key, String message) {
        JSONObject jsonObject ;
        try {
            jsonObject = JSON.parseObject(message);
        }catch (Exception e){
            applicationContext.publishEvent(new SendMessageEvent(new WebSocketMessage(String.format("\n错误的传参，请检查参数格式是否正确",message),key)));
            return;
        }

        String time = jsonObject.getString("time");
        Integer taskId = jsonObject.getInteger("taskId");
        String rowSize = jsonObject.getString("rowSize");
        if (StringUtils.isEmpty(rowSize)) {
            rowSize = "100";
        }
        JobInfo jobInfo = jobService.getById(key);
        if (jobInfo == null) {
            applicationContext.publishEvent(new SendMessageEvent(new WebSocketMessage(String.format("\n任务[%s]信息不存在",key),key)));
            return;
        }
    }

    @Override
    public void close(Session session, String key) {

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
